<?php

class sbUser {

    /**
     * 03/01/2014
     * @param type $device_id
     * @param type $device_type
     * @return int
     */
    static public function getInitional($device_id, $device_type) {
        $user = tblUserTable::getInstance()->findByDql("device_id=?", $device_id)->getFirst();

        if ($user) {
            if ($user->getActive()) {
                if ($user->getCustomerId() == 0) {
                    return sbValues::ERORR_CUSTOMER_NOT_EXISTS;
                } else {
                    $data = array();

                    $arrFamily = 0;
                    $family = tblUserTable::getInstance()->findByDql("customer_id=? and active=? and id<>?", array($user->getCustomerId(), true, $user->getId()));
                    if ($family) {
                        $arrFamily = array();
                        foreach ($family as $f) {
                            array_push($arrFamily, $f->toArray());
                        }
                    }

                    $customerData = 0;
                    $customer = tblCustomersTable::getInstance()->findByDql("id=? and active=?", array($user->getCustomerId(), true))->getFirst();
                    if ($customer) {
                        $customerData = $customer->toArray();
                    }

                    $arrGroup = 0;
                    if ($user->getGroupId() != 0) {
                        $group = tblGroupsTable::getInstance()->findByDql("id=? and active=?", array($user->getGroupId(), true))->getFirst();
                        if ($group) {
                            $arrGroup = $group->toArray();
                        }
                    }

                    $arrUserGroup = 0;
                    $gusers = tblUserTable::getInstance()->findByDql("group_id=? and active=? and id<>?", array($user->getGroupId(), true, $user->getId()));
                    if ($gusers) {
                        $arrUserGroup = array();
                        foreach ($gusers as $g) {
                            array_push($arrUserGroup, $g->toArray());
                        }
                    }

                    $cityData = 0;
                    $city = tblSettlementTable::getInstance()->findByDql("id=?", $user->getSettlementId())->getFirst();
                    if ($city) {
                        $cityData = $city->toArray();
                    }

                    $data = array("user" => $user->toArray(), "family" => $arrFamily, "group" => $arrGroup, "group_users" => $arrUserGroup, "city" => $cityData, "customer" => $customerData);
                    return $data;
                }
            } else {
                return sbValues::STATUS_DEACTIVE;
            }
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    static public function firstLevelRegistration($device_id, $device_type, $first_name, $last_name, $mobile, $settlement_id, $latitude, $longitude, $notif_id) {
        $isNewUser = "new";
        $customer;

        $group = tblGroupsTable::getInstance()->findByDql('settlements_id=? and active=?', array($settlement_id, true))->getFirst();
        if ($group) {
            $group_id = $group->getId();
        } else {
            $group_id = 0;
        }

        $user = tblUserTable::getInstance()->findByDql("mobile=?", $mobile)->getFirst();
        if ($user && $user->getActive()) {
            $user->setDeviceId($device_id);
            $user->setDeviceType($device_type);
            $user->setDeviceNotifId($notif_id);
            $user->setSettlementId($settlement_id);
            $user->setUserLatitude($latitude);
            $user->setUserLongitude($longitude);
            if ($user->getGroupId() == 0) {
                $user->setGroupId($group_id);
                if ($group_id != 0) {
                    $group->setGroupUsers($group->getGroupUsers() + 1);
                    $group->save();
                }
            } else {
                $group = tblGroupsTable::getInstance()->findByDql('id=? and active=?', array($user->getGroupId(), true))->getFirst();
            }
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            $isNewUser = "exists";
            $c = tblCustomersTable::getInstance()->findByDql("id=?", $user->getCustomerId())->getFirst();
        } else if ($user && !$user->getActive()) {
            $user->setDeviceId($device_id);
            $user->setDeviceType($device_type);
            $user->setDeviceNotifId($notif_id);
            $user->setFirstName(urldecode($first_name));
            $user->setLastName(urldecode($last_name));
            $user->setSettlementId($settlement_id);
            $user->setUserLatitude($latitude);
            $user->setUserLongitude($longitude);
            $user->setActive(true);
            if ($user->getGroupId() == 0) {
                $user->setGroupId($group_id);
                if ($group_id != 0) {
                    $group->setGroupUsers($group->getGroupUsers() + 1);
                    $group->save();
                }
            }
            $user->setCreateTime(sbCustomer::getCurrentTime());
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            $isNewUser = "new";
            $c = NULL;
        } else {
            $user = new tblUser();
            $user->setDeviceId($device_id);
            $user->setDeviceType($device_type);
            $user->setDeviceNotifId($notif_id);
            $user->setMobile($mobile);
            $user->setFirstName(urldecode($first_name));
            $user->setLastName(urldecode($last_name));
            $user->setSettlementId($settlement_id);
            $user->setCustomerId(0);
            $user->setUserLatitude($latitude);
            $user->setUserLongitude($longitude);
            $user->setActive(true);
            $user->setGroupId($group_id);
            if ($group_id != 0) {
                $group->setGroupUsers($group->getGroupUsers() + 1);
                $group->save();
            }
            $user->setCreateTime(sbCustomer::getCurrentTime());
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            $isNewUser = "new";
            $c = NULL;
        }

        if ($c) {
            $customer = $c->toArray();
        } else {
            $customer = NULL;
        }

        if ($group) {
            return array("user" => $isNewUser, "id" => $user->toArray(), "customer" => $customer, "group" => $group->toArray());
        } else {
            return array("user" => $isNewUser, "id" => $user->toArray(), "customer" => $customer, "group" => null);
        }
    }

    /**
     * new 30/12/13
     * @param type $parameters - device_id, mobile, first_name, last_name, birthday, sex, email, emergency, vigilante, range
     * @param type $customer
     * @return new tblUser object user
     */
    static public function createNewMainUser($user_id, $email, $birthday, $sex, $street, $home, $phone = null, $apartament = null, $photo = null) {

        $user = tblUserTable::getInstance()->findByDql("id=?", $user_id)->getFirst();


        if ($user) {

            if ($user->getCustomerId() == 0) {
                $user->setCustomerId(sbCustomer::createNewCustomer($user->getCustomerId(), $user->getSettlementId(), urldecode($street), urldecode($home), urldecode($apartament), $phone));
            }

            if ($photo) {
                try {
                    $binary = base64_decode($photo);
                    $path = sfConfig::get('sf_upload_dir') . '/' . $user->getId() . ".png";
                    $success = file_put_contents($path, $binary);

//                    $url = "http://www.azusdex.webcopo.com/FriendlyGuard/web/uploads/" . $user->getId() . ".png";
                    $url = "http://www.friendlyguard.co.il/FriendlyGuard/web/uploads/" . $user->getId() . ".png";

                    $user->setPhoto($url);
                } catch (Exception $e) {
                    
                }
            }

            $user->setBirthday($birthday);
            $user->setAge(self::getUserAge($birthday));
            $user->setSex($sex);
            $user->setEmail($email);
            $user->setMainInHome(true);
            $user->setPermission(sbValues::PERMISSION_STANDART);
            $user->setActive(sbValues::STATUS_ACTIVE);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->setCreateTime(sbCustomer::getCurrentTime());
            $user->save();

            $result = self::getInitional($user->getDeviceId(), $user->getDeviceType());

            //send notif welcome
            $message = 'הינך מוזמן להוסיף את בני משפחתך,הכנס לאזור האישי';
            $msg = array(
                "type" => sbValues::NOTIF_TYPE_WELCOM,
                "message" => $message,
            );
            $notif_id = array($user->getDeviceNotifId());
            $fields = array("registration_ids" => $notif_id, "data" => $msg);
            $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
            $url = 'https://android.googleapis.com/gcm/send';

            if ($user->getDeviceType == sbValues::DEVICE_ANDROID) {
                self::sendAndroidPush($url, $headers, $fields);
            } else {
//                $message = json_encode(array('type' => sbValues::NOTIF_TYPE_WELCOM));
                self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_WELCOM, 0, 0, $notif_id);
            }

            $group = tblGroupsTable::getInstance()->findByDql("id=?", $user->getGroupId())->getFirst();
            if ($group) {
                $group->setGroupUsers($group->getGroupUsers() + 1);
                $group->save();

                return array("user" => $result["user"], "family" => $result["family"], "group" => $group->toArray(), "group_users" => $result["group_users"], "city" => $result["city"], "customer" => $result["customer"]);
            } else {
                return self::getInitional($user->getDeviceId(), $user->getDeviceType());
            }
        } else {
            return FALSE;
        }
    }

    /**
     * 01/01/2014
     * @param type $user_id
     * @param type $first_name
     * @param type $last_name
     * @param type $city
     * @param type $mobile
     * @param type $home
     * @param type $apartament
     * @param type $phone
     * @param type $sex
     * @param type $birthday
     * @param type $photo
     * @param type $email
     * @param type $street
     * @param type $detection
     * @return type
     */
    static public function editUser($user_id, $first_name, $last_name, $city, $mobile, $home, $apartament, $phone, $sex, $birthday, $photo, $email, $street, $detection) {
        $user = tblUserTable::getInstance()->findByDql("id=?", $user_id)->getFirst();
        if ($user) {
            if ($first_name) {
                $user->setFirstName($first_name);
            }

            if ($last_name) {
                $user->setLastName($last_name);
            }

            if ($mobile) {
                $user->setMobile($mobile);
            }

            if ($sex) {
                $user->setSex($sex);
            }

            if ($birthday) {
                $user->setBirthday($birthday);
                $user->setAge(self::getUserAge($birthday));
            }

            if ($photo && $photo != 'null') {
                try {
                    $binary = base64_decode($photo);
                    $path = sfConfig::get('sf_upload_dir') . '/' . $user->getId() . ".png";
                    $success = file_put_contents($path, $binary);

//                    $url = "http://www.azusdex.webcopo.com/FriendlyGuard/web/uploads/" . $user->getId() . ".png";
                    $url = "http://www.friendlyguard.co.il/FriendlyGuard/web/uploads/" . $user->getId() . ".png";

                    $user->setPhoto($url);
                } catch (Exception $e) {
                    
                }
            }

            if ($email) {
                $user->setEmail($email);
            }

            if ($detection) {
                $user->setRangeUpdate(true);
            } else {
                $user->setRangeUpdate(false);
            }

            $user->setUpdateTime(sbCustomer::getCurrentTime());

            if ($user->getMainInHome()) {
                $customer = tblCustomersTable::getInstance()->findByDql("id=?", $user->getCustomerId())->getFirst();
                if ($customer) {
                    if ($city) {
                        $settlement = tblSettlementTable::getInstance()->findByDql("id=?", $customer->getSettlementId())->getFirst();
                        if ($settlement) {
                            if ($settlement->getName() != $city) {
                                $exists = tblSettlementTable::getInstance()->findByDql("name=?", $city)->getFirst();
                                if (!$exists) {
                                    $settlement = sbCustomer::createNewSettlement($city, 0);
                                } else {
                                    $settlement = $exists->getId();
                                }
                                $customer->setSettlementId($settlement);
                                $user->setSettlementId($settlement);
                            }
                        }
                    }

                    if ($street) {
                        $customer->setHomeStreet($street);
                    }

                    if ($home) {
                        $customer->setHomeNumber($home);
                    }

                    if ($apartament) {
                        $customer->setHomeApartamnet($apartament);
                    }

                    if ($phone) {
                        $customer->setHomePhone($phone);
                    }

                    if ($street || $home) {
                        $address = 'ישראל' . " " . $city . " " . $street . " " . $home;

                        $coor = sbValues::getGeolocation($address);

                        if ($coor != sbValues::NOT_FOUND) {
                            $customer->setHomeLatitude($coor['latitude']);
                            $customer->setHomeLongitude($coor['longitude']);
                        }
                    }

                    $customer->save();
                } else {
                    return sbValues::ERORR_CUSTOMER_NOT_EXISTS;
                }
            }

            $user->save();

            return $user->toArray();
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    /**
     * 1/01/2014
     * @param type $customer_id
     * @param type $first_name
     * @param type $last_name
     * @param type $mobile
     * @param type $birthday
     * @return type
     */
    static public function insertFamilyUser($user_id, $edit_id, $first_name, $last_name, $mobile, $birthday) {
        $customer = tblUserTable::getInstance()->findByDql('id=? and active=? and main_in_home=?', array($user_id, true, true))->getFirst();
        if ($customer) {
            if ($edit_id != 0) {
                $edit = tblUserTable::getInstance()->findByDql("id=? and customer_id=? and active=?", array($edit_id, $customer->getCustomerId(), true))->getFirst();
                if ($edit) {
                    $edit->setFirstName($first_name);
                    $edit->setLastName($last_name);
                    $edit->setMobile($mobile);
                    $edit->setBirthday($birthday);
                    $edit->setUpdateTime(sbCustomer::getCurrentTime());
                    $edit->save();

                    return $edit->toArray();
                } else {
                    return sbValues::ERORR_USER_NOT_EXISTS;
                }
            } else {
                $user = tblUserTable::getInstance()->findByDql('mobile=?', $mobile)->getFirst();
                if ($user && $user->getActive() == true) {
                    return sbValues::ERORR_USER_EXISTS;
                } else if ($user && $user->getActive() == false) {
                    $user->setCustomerId($customer->getCustomerId());
                    $user->setSettlementId($customer->getSettlementId());
                    $user->setFirstName($first_name);
                    $user->setLastName($last_name);
                    $user->setBirthday($birthday);
                    $user->setAge(self::getUserAge($birthday));
                    $user->setActive(true);
                    $user->setGroupId($customer->getGroupId());
                    $user->setUpdateTime(sbCustomer::getCurrentTime());
                    $user->setPermission(sbValues::PERMISSION_CHILD);
                    $user->save();

                    if ($customer->getGroupId() != 0) {
                        $group = tblGroupsTable::getInstance()->findByDql("id=? and active=?", array($customer->getGroupId(), true))->getFirst();
                        if ($group) {
                            $group->setGroupUsers($group->getGroupUsers() + 1);
                            $group->save();
                        }
                    }

                    return $user->toArray();
                } else {
                    $user = new tblUser();
                    $user->setCustomerId($customer->getCustomerId());
                    $user->setSettlementId($customer->getSettlementId());
                    $user->setFirstName($first_name);
                    $user->setLastName($last_name);
                    $user->setMobile($mobile);
                    $user->setBirthday($birthday);
                    $user->setAge(self::getUserAge($birthday));
                    $user->setActive(true);
                    $user->setGroupId($customer->getGroupId());
                    $user->setUpdateTime(sbCustomer::getCurrentTime());
                    $user->setCreateTime(sbCustomer::getCurrentTime());
                    $user->setPermission(sbValues::PERMISSION_CHILD);
                    $user->save();

                    if ($customer->getGroupId() != 0) {
                        $group = tblGroupsTable::getInstance()->findByDql("id=? and active=?", array($customer->getGroupId(), true))->getFirst();
                        if ($group) {
                            $group->setGroupUsers($group->getGroupUsers() + 1);
                            $group->save();
                        }
                    }

                    return $user->toArray();
                }
            }
        } else {
            return sbValues::ERORR_CUSTOMER_NOT_EXISTS;
        }
    }

    /**
     * 02/01/2014
     * 
     */
    static public function getFamily($user_id, $device_id) {
        $user = tblUserTable::getInstance()->findByDql("id=? and device_id=? and active=?", array($user_id, $device_id, true))->getFirst();
        if ($user) {
            $users = tblUserTable::getInstance()->findByDql("customer_id=? and active=?", array($user->getCustomerId(), true));

            $arrUsers = array();
            foreach ($users as $u) {
                array_push($arrUsers, $u->toArray());
            }

            return $arrUsers;
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    /**
     * 3/01/2014
     * @param type $user_id
     * @param type $find_id
     * @return type
     */
    static public function getMemberFamilyLocation($user_id, $find_id) {
        $user_id = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        $find_id = tblUserTable::getInstance()->findByDql("id=? and active=?", array($find_id, true))->getFirst();

        if ($find_id && $user_id) {
            if ($find_id->getCustomerId() == $user_id->getCustomerId()) {
                if ($find_id->getRangeUpdate()) {
                    if ($find_id->getUserLatitude() && $find_id->getUserLongitude()) {
                        return array("latitude" => $find_id->getUserLatitude(), "longitude" => $find_id->getUserLongitude(), "time" => $find_id->getUpdateTime());
                    } else {
                        return sbValues::NOT_FOUND;
                    }
                } else {
                    return sbValues::PERMISSION_STANDART;
                }
            } else {
                return;
            }
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    /**
     * 03/01/2014
     * @param type $user_id
     * @param type $delete_id
     * @return type
     */
    static public function deleteFamilyMember($user_id, $delete_id) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=? and main_in_home=?", array($user_id, true, true))->getFirst();
        if ($user) {
            $delete = tblUserTable::getInstance()->findByDql("id=?", $delete_id)->getFirst();
            if ($delete) {
                if ($user->getCustomerId() == $delete->getCustomerId()) {
                    $group = tblGroupsTable::getInstance()->findByDql("id=? and active=?", array($delete->getGroupId(), true))->getFirst();
                    if ($group) {
                        $group->setGroupUsers($group->getGroupUsers() - 1);
                        $group->save();
                    }
                    $delete->setCustomerId(0);
                    $delete->setDeviceId(0);
                    $delete->setDeviceType(0);
                    $delete->setDeviceNotifId(0);
                    $delete->setPermission(0);
                    $delete->setGroupId(0);
                    $delete->setActive(sbValues::STATUS_DEACTIVE);
                    $delete->setUpdateTime(sbCustomer::getCurrentTime());
                    $delete->save();

                    return sbValues::SUCCESS;
                }
            } else {
                return sbValues::ERORR_USER_NOT_EXISTS;
            }
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    /**
     * 3/01/2014
     * @param type $user_id
     * @param type $group_name
     * @return type
     */
    static public function createNewGroup($user_id, $group_name) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=? and main_in_home=?", array($user_id, true, true))->getFirst();
        if ($user) {
            $count_users = 0;
            $group = tblGroupsTable::getInstance()->findByDql("group_name=?", $group_name)->getFirst();
            if ($group) {
                $group->setCraatedBy($user_id);
                $group->setCreateTime(sbCustomer::getCurrentTime());
                $group->setUpdateTime(sbCustomer::getCurrentTime());
                $group->save();
            } else {
                $group = new tblGroups();
                $group->setGroupName($group_name);
                $group->setCraatedBy($user_id);
                $group->setCreateTime(sbCustomer::getCurrentTime());
                $group->setUpdateTime(sbCustomer::getCurrentTime());
                $group->save();
            }
            $users = tblUserTable::getInstance()->findByDql("customer_id=?", $user->getCustomerId());
            $arrGroupUsers = 0;
            if ($users) {
                $arrGroupUsers = array();
                foreach ($users as $u) {
                    $u->setGroupId($group->getId());
                    $u->save();
                    if ($u->getId() != $user_id) {
                        array_push($arrGroupUsers, $u->toArray());
                    }
                    $count_users++;
                }

                if ($count_users > 0) {
                    $group->setGroupUsers($count_users);
                    $group->save();
                }
            }

            return array('group' => $group->toArray(), 'group_users' => $arrGroupUsers);
        } else {
            return sbValues::PERMISSION_STANDART;
        }
    }

    /**
     * 4/01/2014
     * @param type $user_id
     * @return type
     */
    static public function disconnectFromGroup($user_id) {
        $user = tblUserTable::getInstance()->findByDql("id=? and main_in_home=? and active=?", array($user_id, true, true))->getFirst();
        if ($user) {
            if ($user->getGroupId() > 0) {
                $usersInGroup = 0;
                $groupId = $user->getGroupId();

                $group = tblGroupsTable::getInstance()->findByDql("id=? and active=? and is_settlements=?", array($groupId, true, false))->getFirst();
                if ($group) {
                    //delete main user from group
                    $user->setGroupId(0);
                    $user->save();
                    $usersInGroup++;

                    $family = tblUserTable::getInstance()->findByDql("customer_id=? and active=? and main_in_home=?", array($user->getCustomerId(), true, false));
                    if ($family) {
                        foreach ($family as $f) {
                            $f->setGroupId(0);
                            $f->save();
                            $usersInGroup++;
                        }
                    }

                    $group->setGroupUsers($group->getGroupUsers() - $usersInGroup);
                    $group->save();

                    return sbValues::SUCCESS;
                } else {
                    return sbValues::PERMISSION_STANDART;
                }
            } else {
                return sbValues::PERMISSION_STANDART;
            }
        } else {
            return sbValues::PERMISSION_STANDART;
        }
    }

    /**
     * 4/01/2014
     * @param type $group_id
     * @param type $number
     * @param type $first_name
     * @param type $last_name
     * @return type
     */
    static public function inviteFriendToGroup($group_id, $number, $first_name, $last_name) {
        $group = tblGroupsTable::getInstance()->findByDql("id=? and active=?", array($group_id, true))->getFirst();
        $user = tblUserTable::getInstance()->findByDql("mobile=?", $number)->getFirst();
        if ($user && $group) {
            if ($user->getMainInHome() && $user->getActive()) {
                $user->setGroupId($group_id);
                $user->save();
                $countUsers = 1;

                $users = tblUserTable::getInstance()->findByDql("customer_id=? and active=? and main_in_home=?", array($user->getCustomerId(), true, false));
                if ($users) {
                    foreach ($users as $u) {
                        $u->setGroupId($group_id);
                        $u->save();
                        $countUsers++;
                    }
                }

                $group->setGroupUsers($countUsers);
                $group->save();

                return sbValues::SUCCESS;
            }
        } else {
            if ($group) {
                $user = new tblUser();
                $user->setActive(false);
                $user->setMobile($number);
                $user->setGroupId($group_id);
                $user->save();

                return sbValues::ERORR_USER_NOT_EXISTS;
            } else {
                return sbValues::NOT_FOUND;
            }
        }
    }

    /**
     * 5/01/2014
     * @param type $user_id
     * @param type $lat
     * @param type $long
     * @return type
     */
    static public function updateLocation($user_id, $lat, $long) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setUserLatitude($lat);
            $user->setUserLongitude($long);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function findMyDevice($user_id, $find) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setRangeUpdate($find);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function statusShabat($user_id, $shabat) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setShabat($shabat);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function getMePushRadius($user_id, $radius) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setInRadius($radius);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function settingsVigilante($user_id, $val) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setVigilante($val);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function settingsEmergency($user_id, $val) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setEmergency($val);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function settingsParents($user_id, $val) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $user->setParents($val);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();

            return sbValues::SUCCESS;
        }

        return sbValues::NOT_FOUND;
    }

    static public function userCreateHomeAlarm($user_id) {
        $distance = 10;
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $family = tblUserTable::getInstance()->findByDql("customer_id=? and active=?", array($user->getCustomerId(), true));
            //family array
            $arrFamily = array();
            foreach ($family as $f) {
                array_push($arrFamily, $f->toArray());
            }
            //message array
            $message = $user->getFirstName() . " " . $user->getLastName() . " " . "הפעיל אזעקה בבית";
            //customer array
            $customer = tblCustomersTable::getInstance()->findByDql("id=? and active=?", array($user->getCustomerId(), true))->getFirst();
            //get distance
            $c = self::getDistance3($customer->getHomeLatitude(), $customer->getHomeLongitude());
            //find all users in group in distance < $distance
            $g = Doctrine_Query::create()->
                    select('*, ' . $c . ' AS distance')->
                    from('tblUser')->
                    where('active=? and group_id=? and age>? and id<>? and shabat=?', array(true, $user->getGroupId(), 13, $user->getId(), false))->
                    having('distance < ' . intval($distance))->
                    orderBy('distance')->
                    execute();

            $r = Doctrine_Query::create()->
                    select('*, ' . $c . ' AS distance')->
                    from('tblUser')->
                    where('active=? and group_id=? and age>? and id<>? and shabat=? and in_radius=?', array(true, $user->getGroupId(), 13, $user->getId(), false, true))->
                    having('distance > ' . intval($distance))->
                    orderBy('distance')->
                    execute();

            $alert = new tblAlert();
            $alert->setUserId($user_id);
            $alert->setGroupId($user->getGroupId());
            $alert->setLatitude($customer->getHomeLatitude());
            $alert->setLongitude($customer->getHomeLongitude());
            $alert->setType(sbValues::ALARM_HOME);
            $alert->setStatus(sbValues::ALARM_OPEN);
            $alert->setStartTime(sbCustomer::getCurrentTime());
            $alert->save();

            if ($g) {
                foreach ($g as $p) {
                    $msg = array(
                        "type" => sbValues::NOTIF_TYPE_HOME,
                        "message" => $message,
                        "time" => sbCustomer::getCurrentTime(),
                        "alert" => array("message" => $message, "alert" => $alert->toArray())
                    );
                    $notif_id = array($p->getDeviceNotifId());
                    $fields = array("registration_ids" => $notif_id, "data" => $msg);
                    $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                    $url = 'https://android.googleapis.com/gcm/send';

                    if ($p->getDeviceId() == sbValues::DEVICE_ANDROID) {
                        self::sendAndroidPush($url, $headers, $fields);
                    } else {
//                        $message = json_encode(array('type' => sbValues::NOTIF_TYPE_HOME, 'alert' => $alert->getId()));
                        self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_HOME, $alert->getId(), 0, $notif_id);
                    }
                }
            }

            if ($r) {
                foreach ($r as $p) {
                    $msg = array(
                        "type" => sbValues::NOTIF_TYPE_HOME,
                        "message" => $message,
                        "time" => sbCustomer::getCurrentTime(),
                        "alert" => array("message" => $message, "alert" => $alert->toArray())
                    );
                    $notif_id = array($p->getDeviceNotifId());
                    $fields = array("registration_ids" => $notif_id, "data" => $msg);
                    $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                    $url = 'https://android.googleapis.com/gcm/send';

                    if ($p->getDeviceId() == sbValues::DEVICE_ANDROID) {
                        self::sendAndroidPush($url, $headers, $fields);
                    } else {
//                        $message = json_encode(array('type' => sbValues::NOTIF_TYPE_HOME, 'alert' => $alert->getId()));
                        self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_HOME, $alert->getId(), 0, $notif_id);
                    }
                }
            }

            return array("message" => $message, "alert" => $alert->toArray());
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    static public function userCreateSosAlarm($user_id, $lat, $long) {
        $distance = 5;
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            //get distance
            $c = self::getDistance3($lat, $long);
            //find all users in group in distance < $distance
            $g = Doctrine_Query::create()->
                    select('*, ' . $c . ' AS distance')->
                    from('tblUser')->
                    where('active=? and age>? and id<>?', array(true, 13, $user->getId()))->
                    having('distance < ' . intval($distance))->
                    orderBy('distance')->
                    execute();

            $r = Doctrine_Query::create()->
                    select('*, ' . $c . ' AS distance')->
                    from('tblUser')->
                    where('active=? and group_id=? and age>? and id<>? and shabat=? and in_radius=?', array(true, $user->getGroupId(), 13, $user->getId(), false, true))->
                    having('distance > ' . intval($distance))->
                    orderBy('distance')->
                    execute();

            //message array
            $message = $user->getFirstName() . " " . $user->getLastName() . " " . "הפעיל אירוע חירום";

            $alert = new tblAlert();
            $alert->setUserId($user_id);
            $alert->setGroupId($user->getGroupId());
            $alert->setType(sbValues::ALARM_SOS);
            $alert->setStatus(sbValues::ALARM_OPEN);
            $alert->setLatitude($lat);
            $alert->setLongitude($long);
            $alert->setStartTime(sbCustomer::getCurrentTime());
            $alert->save();

            if ($g) {
                foreach ($g as $p) {
                    $msg = array(
                        "type" => sbValues::NOTIF_TYPE_SOS,
                        "message" => $message,
                        "time" => sbCustomer::getCurrentTime(),
                        "alert" => array("message" => $message, "alert" => $alert->toArray())
                    );
                    $notif_id = array($p->getDeviceNotifId());
                    $fields = array("registration_ids" => $notif_id, "data" => $msg);
                    $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                    $url = 'https://android.googleapis.com/gcm/send';

                    if ($p->getDeviceId() == sbValues::DEVICE_ANDROID) {
                        self::sendAndroidPush($url, $headers, $fields);
                    } else {
//                        $message = json_encode(array('type' => sbValues::NOTIF_TYPE_SOS, 'alert' => $alert->getId()));
                        self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_SOS, $alert->getId(), 0, $notif_id);
                    }
                }
            }

            if ($r) {
                foreach ($r as $p) {
                    $msg = array(
                        "type" => sbValues::NOTIF_TYPE_SOS,
                        "message" => $message,
                        "time" => sbCustomer::getCurrentTime(),
                        "alert" => array("message" => $message, "alert" => $alert->toArray())
                    );
                    $notif_id = array($p->getDeviceNotifId());
                    $fields = array("registration_ids" => $notif_id, "data" => $msg);
                    $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                    $url = 'https://android.googleapis.com/gcm/send';

                    if ($p->getDeviceId() == sbValues::DEVICE_ANDROID) {
                        self::sendAndroidPush($url, $headers, $fields);
                    } else {
//                        $message = json_encode(array('type' => sbValues::NOTIF_TYPE_SOS, 'alert' => $alert->getId()));
                        self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_SOS, $alert->getId(), $notif_id);
                    }
                }
            }

            return array("message" => $message, "alert" => $alert->toArray());
        }
    }

    static public function stopAlert($user_id, $alert_id) {
        $user = tblUserTable::getInstance()->findByDql("id=? and active=?", array($user_id, true))->getFirst();
        if ($user) {
            $alert = tblAlertTable::getInstance()->findByDql("id=?", $alert_id)->getFirst();
            if ($alert) {
                $alert->setStatus(sbValues::ALARM_CLOSE);
                $alert->setStopTime(sbCustomer::getCurrentTime());
                $alert->save();
            }

            //get type alert and user 
            $created = tblUserTable::getInstance()->findByDql("id=? and active=?", array($alert->getUserId(), true))->getFirst();
            $customer = tblCustomersTable::getInstance()->findByDql("id=?", $created->getCustomerId())->getFirst();

            if ($alert->getType() == sbValues::ALARM_SOS) {
                $distance = 5;
                //get distance
                $c = self::getDistance3($created->getUserLatitude(), $created->getUserLongitude());
                //find all users in group in distance < $distance
                $g = Doctrine_Query::create()->
                        select('*, ' . $c . ' AS distance')->
                        from('tblUser')->
                        where('active=? and age>? and id<>? and shabat=?', array(true, 13, $user_id, false))->
                        having('distance < ' . intval($distance))->
                        orderBy('distance')->
                        execute();
                $message = "אירוע חירום שנפתח על ידי" . " " . $created->getFirstName() . " " . $created->getLastName() . " " . "טופל";
            } else {
                $distance = 10;
                //get distance
                $c = self::getDistance3($customer->getHomeLatitude(), $customer->getHomeLongitude());
                //find all users in group in distance < $distance
                $g = Doctrine_Query::create()->
                        select('*, ' . $c . ' AS distance')->
                        from('tblUser')->
                        where('active=? and group_id=? and age>? and id<>?', array(true, $user->getGroupId(), 13, $user_id))->
                        having('distance < ' . intval($distance))->
                        orderBy('distance')->
                        execute();
                $message = "אירוע אזעקה בבית של" . " " . $created->getFirstName() . " " . $created->getLastName() . " " . "טופל";
            }

            if ($g) {
                foreach ($g as $p) {
                    $msg = array(
                        "type" => sbValues::NOTIF_TYPE_CLOSE,
                        "message" => $message,
                        "time" => sbCustomer::getCurrentTime(),
                        "alert" => array("message" => $message, "alert" => $alert->toArray())
                    );
                    $notif_id = array($p->getDeviceNotifId());
                    $fields = array("registration_ids" => $notif_id, "data" => $msg);
                    $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                    $url = 'https://android.googleapis.com/gcm/send';

                    if ($p->getDeviceType() == sbValues::DEVICE_ANDROID) {
                        self::sendAndroidPush($url, $headers, $fields);
                    } else {
//                        $message = json_encode(array('type' => sbValues::NOTIF_TYPE_CLOSE, 'alert' => $alert->getId()));
                        self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_CLOSE, $alert->getId(), 0, $notif_id);
                    }
                }
            }

            return array('message' => $message, 'alert' => $alert->toArray());
        }
    }

    static public function connectToAlarm($alert_id, $user_id) {
        $alert = tblAlertTable::getInstance()->findByDql("id=?", $alert_id)->getFirst();
        if ($alert) {
            if ($alert->getStatus() != sbValues::ALARM_WORK && $alert->getStatus() != sbValues::ALARM_CLOSE) {
                $created = tblUserTable::getInstance()->findByDql("id=?", $alert->getUserId())->getFirst();
                $user = tblUserTable::getInstance()->findByDql("id=?", $user_id)->getFirst();


                if ($created) {
                    if (!$user) {
                        return "user";
                    }
                    //save user to connected
                    if (!$alert->getUserIdOne() || $alert->getUserIdOne() == 0) {
                        $alert->setUserIdOne($user_id);
                    } else if (!$alert->getUserIdTwo() || $alert->getUserIdTwo() == 0) {
                        $alert->setUserIdTwo($user_id);
                    } else if (!$alert->getUserIdThree() || $alert->getUserIdThree() == 0) {
                        $alert->setUserIdThree($user_id);
                    } else if (!$alert->getUserIdFour() || $alert->getUserIdFour() == 0) {
                        $alert->setUserIdFour($user_id);
                        $alert->setStatus(sbValues::ALARM_WORK);
                    } else {
                        return $alert->toArray();
                    }
                    $alert->save();

                    //send push to users
                    if ($alert->getType() == sbValues::ALARM_SOS) {
                        $distance = 5;
                        //get distance
                        $c = self::getDistance3($created->getUserLatitude(), $created->getUserLongitude());
                        //find all users in group in distance < $distance
                        $g = Doctrine_Query::create()->
                                select('*, ' . $c . ' AS distance')->
                                from('tblUser')->
                                where('active=? and age>?', array(true, 13))->
                                having('distance < ' . intval($distance))->
                                orderBy('distance')->
                                execute();
                    } else {
                        $customer = tblCustomersTable::getInstance()->findByDql("id=?", $user->getCustomerId())->getFirst();
                        $distance = 10;
                        //get distance
                        $c = self::getDistance3($customer->getHomeLatitude(), $customer->getHomeLongitude());
                        //find all users in group in distance < $distance
                        $g = Doctrine_Query::create()->
                                select('*, ' . $c . ' AS distance')->
                                from('tblUser')->
                                where('active=? and group_id=? and age>?', array(true, $user->getGroupId(), 13))->
                                having('distance < ' . intval($distance))->
                                orderBy('distance')->
                                execute();
                    }

                    $message = $user->getFirstName() . " " . $user->getLastName() . " " . "הצטרף לאירוע";

                    if ($g) {
                        foreach ($g as $p) {
                            $msg = array(
                                "type" => sbValues::NOTIF_TYPE_TO_ALERT,
                                "message" => $message,
                                "time" => sbCustomer::getCurrentTime(),
                                "user" => $user->toArray(),
                                "alert" => array("message" => $message, "alert" => $alert->toArray())
                            );
                            $notif_id = array($p->getDeviceNotifId());
                            $fields = array("registration_ids" => $notif_id, "data" => $msg);
                            $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                            $url = 'https://android.googleapis.com/gcm/send';

                            if ($p->getDeviceType() == sbValues::DEVICE_ANDROID) {
                                self::sendAndroidPush($url, $headers, $fields);
                            } else {
//                                $message = json_encode(array('type' => sbValues::NOTIF_TYPE_TO_ALERT, 'alert' => $alert->getId(), 'user' => $user_id));
                                self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_TO_ALERT, $alert->getId(),  $user_id, $notif_id);
                            }
                        }
                    }

                    $aMessage = new tblMessage();
                    $aMessage->setUserId($user_id);
                    $aMessage->setType($alert->getType());
                    $aMessage->setCreateTime(sbCustomer::getCurrentTime());
                    $aMessage->save();

                    return $alert->toArray();
                } else {
                    return sbValues::ERORR_USER_NOT_EXISTS;
                }
            } else {
                return $alert->toArray();
            }
        } else {
            return sbValues::NOT_FOUND;
        }
    }

    static public function infoAlert($alert_id, $lat, $long) {
        $alert = tblAlertTable::getInstance()->findByDql("id=?", $alert_id)->getFirst();

        if ($alert) {
            if ($alert->getStatus() != sbValues::ALARM_CLOSE) {
                $created = tblUserTable::getInstance()->findByDql("id=?", $alert->getUserId())->getFirst();

                $family = tblUserTable::getInstance()->findByDql("customer_id=? and id<>? and active=? and age>?", array($created->getCustomerId(), $created->getId(), true, 13));
                $familyArr = array();
                if ($family) {
                    foreach ($family as $f) {
                        array_push($familyArr, $f->toArray());
                    }
                }

                $customer = tblCustomersTable::getInstance()->findByDql("id=?", $created->getCustomerId())->getFirst();

                if ($alert->getType() == sbValues::ALARM_HOME) {
                    //get distance
                    if ($customer) {
                        $distance = self::calculateTheDistance($lat, $long, $customer->getHomeLatitude(), $customer->getHomeLongitude());
                        $location = array(
                            "distance" => $distance,
                            "address" => $customer->getHomeStreet() . " " . $customer->getHomeNumber() . " " . $customer->getHomeApartamnet(),
                            "latitude" => $customer->getHomeLatitude(),
                            "logitude" => $customer->getHomeLongitude()
                        );
                    }
                } else {
                    //get distance
                    $distance = self::calculateTheDistance($lat, $long, $created->getUserLatitude(), $created->getUserLongitude());
                    $location = array(
                        "distance" => $distance,
                        "address" => "צפה במפה",
                        "latitude" => $created->getUserLatitude(),
                        "logitude" => $created->getUserLongitude()
                    );
                }

                //get users going to alarm
                $going = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
                $users = array();
                if ($going->getUserIdOne()) {
                    $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($going->getUserIdOne(), true))->getFirst();
                    array_push($users, $u->toArray());
                }

                if ($going->getUserIdTwo()) {
                    $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($going->getUserIdTwo(), true))->getFirst();
                    array_push($users, $u->toArray());
                }

                if ($going->getUserIdThree()) {
                    $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($going->getUserIdThree(), true))->getFirst();
                    array_push($users, $u->toArray());
                }

                if ($going->getUserIdFour()) {
                    $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($going->getUserIdFour(), true))->getFirst();
                    array_push($users, $u->toArray());
                }

                return array("alert" => $alert->toArray(), "user" => $created->toArray(), "customer" => $customer->toArray(), "family" => $familyArr, "location" => $location, "users" => $users);
            } else {
                return sbValues::ALARM_CLOSE;
            }
        } else {
            return sbValues::NOT_FOUND;
        }
    }

    static public function sendPushInAlert($user_id, $alert_id, $message) {
        $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
        if ($alert) {
            $users = array();
            $isNotCommander = false;
            //send to helseft
            if ($alert->getUserId()) {
                if ($user_id === $alert->getUserId()) {
                    $isNotCommander = true;
                }
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($alert->getUserId(), true))->getFirst();
                array_push($users, $u);
            }

            if ($alert->getUserIdOne()) {
                if ($user_id === $alert->getUserIdOne()) {
                    $isNotCommander = true;
                }
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($alert->getUserIdOne(), true))->getFirst();
                array_push($users, $u->toArray());
            }

            if ($alert->getUserIdTwo()) {
                if ($user_id === $alert->getUserIdTwo()) {
                    $isNotCommander = true;
                }
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($alert->getUserIdTwo(), true))->getFirst();
                array_push($users, $u->toArray());
            }

            if ($alert->getUserIdThree()) {
                if ($user_id === $alert->getUserIdThree()) {
                    $isNotCommander = true;
                }
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($alert->getUserIdThree(), true))->getFirst();
                array_push($users, $u->toArray());
            }

            if ($alert->getUserIdFour()) {
                if ($user_id === $alert->getUserIdFour()) {
                    $isNotCommander = true;
                }
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($alert->getUserIdFour(), true))->getFirst();
                array_push($users, $u->toArray());
            }

            if (!$isNotCommander) {
                $u = tblUserTable::getInstance()->findByDql('id=? and active=?', array($user_id, true))->getFirst();
                array_push($users, $u->toArray());
            }
        }

        $new_message = new tblMessage();
        $new_message->setUserId($user_id);
        $new_message->setAlertId($alert_id);
        $new_message->setText($message);
        $new_message->setCreateTime(sbCustomer::getCurrentTime());
        $new_message->save();

        $user = tblUserTable::getInstance()->findByDql('id=?', $user_id)->getFirst();

        $msg = array(
            "type" => sbValues::NOTIF_TYPE_UPDATE,
            "message" => $message,
            "time" => sbCustomer::getCurrentTime(),
            "user" => $user->toArray(),
            "alert" => array("message" => $message, "alert" => $alert->toArray())
        );

        if ($users) {
            foreach ($users as $u) {
                $notif_id = array($u['device_notif_id']);
                $fields = array("registration_ids" => $notif_id, "data" => $msg);
                $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                $url = 'https://android.googleapis.com/gcm/send';

                if ($u['device_type'] == sbValues::DEVICE_ANDROID) {
                    self::sendAndroidPush($url, $headers, $fields);
                } else {
//                    $message = json_encode(array('type' => sbValues::NOTIF_TYPE_UPDATE, 'alert' => $alert->getId(), 'message' => $new_message->getId()));
                    self::sendIponePush('FriendyGuard', sbValues::NOTIF_TYPE_UPDATE, $alert->getId(), $new_message->getId(), $notif_id);
                }
            }
        }

        return $users;
    }

    static public function sendAndroidPush($url, $headers, $fields) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    static public function sendIponePush($message, $message_id, $param_one, $param_two, $notif_id) {
        $badge = 2;
        $apns = new APNS_Push();

        $apns->connectToAPNS();
        $payload = $apns->makePayload($message, $message_id, $param_one, $param_two, $badge);
        $result = $apns->send($notif_id, $payload);
        return $result;
    }

    static public function getDistance($latitude, $longitude, $distance) {
        $connection = Doctrine_Manager::connection();
        $query = 'SELECT '
                . '(6371 * acos(cos(radians(' . $latitude
                . '))*cos(radians(user_latitude))*cos(radians(user_longitude)-radians(' . $longitude
                . '))+sin(radians(' . $latitude
                . '))*sin(radians(user_latitude)))) AS distance '
                . 'FROM tbl_user WHERE active=' . true . ' having distance < ' . intval($distance) . ' ORDER BY distance';
        $statement = $connection->execute($query);
        $statement->execute();
        $resultset = $statement->fetch(PDO::FETCH_OBJ);

        return $resultset;
    }

    static public function getMyDistance($lat1, $long1, $lat2, $long2) {
        $theta = $long1 - $long2;

        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;

        return ($miles * 1.609344);
    }

    static public function calculateTheDistance($lat1, $long1, $lat2, $long2) {
        // перевести координаты в радианы
        $lat1 = deg2rad($lat1);
        $lat2 = deg2rad($lat2);
        $long1 = deg2rad($long1);
        $long2 = deg2rad($long2);

        // косинусы и синусы широт и разницы долгот
        $cl1 = cos($lat1);
        $cl2 = cos($lat2);
        $sl1 = sin($lat1);
        $sl2 = sin($lat2);
        $delta = $long2 - $long1;
        $cdelta = cos($delta);
        $sdelta = sin($delta);

        // вычисления длины большого круга
        $y = sqrt(pow($cl2 * $sdelta, 2) + pow($cl1 * $sl2 - $sl1 * $cl2 * $cdelta, 2));
        $x = $sl1 * $sl2 + $cl1 * $cl2 * $cdelta;

        //
        $ad = atan2($y, $x);
        $dist = $ad * sbValues::EARTH_RADIUS_MR;

        $dist = round($dist, 2);

        return $dist;
    }

    static public function getDistance2($lat, $long) {
        $c1 = "POW(SIN(RADIANS($lat - user_latitude)), 2)";
        $c1.= "+COS(RADIANS($lat)) * COS(RADIANS(user_latitude))";
        $c1.= "POW(SIN(RADIANS($long - user_longitude)), 2)";
        $s = "SQRT($c1)";
        $r = sbValues::EARTH_RADIUS_KM * 2 * "ASIN($s)";
        return $r;
    }

    static public function getDistance3($lat, $long) {
        $qry = "(((acos(sin((" . $lat . "*pi()/180))*sin((user_latitude*pi()/180))+cos((" . $lat . "*pi()/180))*"
                . "cos((user_latitude*pi()/180)) * cos(((" . $long . "-user_longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344)";

        return $qry;
    }

    /**
     * 
     */
    static public function _getHaversineWithAntipodDotsDistanceCondition($latitude, $longitude) {
        $numerator = 'POW(COS(RADIANS(user_latitude)) * SIN(ABS(RADIANS(' . $longitude . ')-RADIANS(user_longitude))),2)';

        $numerator .= ' + POW(  COS(RADIANS(' . $latitude . ')) * SIN(RADIANS(user_latitude)) - SIN(RADIANS(' . $latitude . '))
                        * COS(RADIANS(user_latitude))*COS(ABS(RADIANS(' . $longitude . ')-RADIANS(user_longitude)))
                        ,2)';
        $numerator = 'SQRT(' . $numerator . ')';

        $denominator = 'SIN(RADIANS(user_latitude))*SIN(RADIANS(' . $latitude . ')) +
                        COS(RADIANS(user_latitude))*COS(RADIANS(' . $latitude . '))*
                        COS(ABS(RADIANS(' . $longitude . ')-RADIANS(user_longitude)))';

        $condition = 'ATAN(' . $numerator . '/(' . $denominator . ')) * ' . sbValues::EARTH_RADIUS_KM;

        return $condition;
    }

    /**
     * deactive current user
     * @param type $device_id - main user
     * @param type $user_id - user to delete, family memeber
     * @return int 1 - success
     */
    static public function deleteUser($device_id, $user_id) {
        $user = tblUserTable::getInstance()->findByDql('device_id=?', $device_id)->getFirst();
        if ($user && $user->getActive() == sbValues::STATUS_ACTIVE && $user->getMainInHome() == sbValues::STATUS_ACTIVE) {
            var_dump($user->getCustomerId(), $user_id);
            $remove = tblUserTable::getInstance()->findByDql('customer_id=? and id=?', array($user->getCustomerId(), $user_id))->getFirst();
            if ($remove->getDeviceId() == $device_id) {
                return sbValues::ERORR_USER_CAN_NOT_REMOVE_HIMSELF;
            }

            if ($remove) {
                $remove->setActive(sbValues::STATUS_DEACTIVE);
                $remove->save();

                return 1;
            } else {
                return sbValues::ERORR_USER_NOT_EXISTS;
            }
        } else {
            return sbValues::ERORR_NOT_PERMISSIONS;
        }
    }

    /**
     * customer (or main user) insert new user to data base, family member
     * @param type $first_name
     * @param type $last_name
     * @param type $birthday
     * @param type $sex
     * @param type $mobile
     * @param type $device_id
     * @return \tblUser object new user
     */
    static public function addNewUser($first_name, $last_name, $birthday, $sex, $mobile, $device_id) {
        if (isset($device_id)) {
            $main_user = tblUserTable::getInstance()->findByDql('device_id=? and active=? and main_in_home=?', array($device_id, true, true))->getFirst();
            if (!$main_user) {
                return sbValues::ERORR_USER_NOT_EXISTS;
            }
        } else {
            return sbValues::ERORR_INCORECT_VALUES;
        }

        $customer = tblCustomersTable::getInstance()->findByDql('id=? and active=?', array($main_user->getCustomerId(), true))->getFirst();
        if (!$customer) {
            return sbValues::ERORR_CUSTOMER_NOT_EXISTS;
        }

        $user_exists = tblUserTable::getInstance()->findByDql('mobile=?', $mobile)->getFirst();
        if ($user_exists) {
            return sbValues::ERORR_USER_EXISTS;
        }

        $user = new tblUser();
        $user->setCustomerId($customer->getId());
        $user->setSettlementId($customer->getSettlementId());
        $user->setFirstName($first_name);
        $user->setLastName($last_name);
        $user->setBirthday($birthday);
        $user->setSex($sex);
        $user->setMobile($mobile);
        $user->setUserLatitude($customer->getHomeLatitude());
        $user->setUserLongitude($customer->getHomeLongitude());
        $user->setActive(sbValues::STATUS_ACTIVE);
        $user->setUpdateTime(sbCustomer::getCurrentTime());
        $user->setCreateTime(sbCustomer::getCurrentTime());
        $user->save();

        return $user;
    }

    static public function editUserToUser($parameters) {
        if (isset($parameters['device_id']) && isset($parameters['device_type'])) {
            $user = tblUserTable::getInstance()->findByDql('device_id=? and active=?', array($parameters['device_id'], true))->getFirst();
            if ($user) {
                if (isset($parameters['photo']))
                    $user->setPhoto($parameters['photo']);
                if (isset($parameters['birthday']))
                    $user->setBirthday($parameters['birthday']);
                if (isset($parameters['first_name']))
                    $user->setFirstName($parameters['first_name']);
                if (isset($parameters['last_name']))
                    $user->setLastName($parameters['last_name']);
                if (isset($parameters['mobile']))
                    $user->setMobile($parameters['mobile']);
                if (isset($parameters['email']))
                    $user->setEmail($parameters['email']);
                if (isset($parameters['range']))
                    $user->setRangeUpdate($parameters['range']);
                $user->setDeviceType($paramenters['device_type']);
                $user->setUpdateTime(sbCustomer::getCurrentTime());
                $user->save();
                return sbValues::SUCCESS;
            } else {
                return sbValues::ERORR_USER_NOT_EXISTS;
            }
        } else {
            return sbValues::ERORR_INCORECT_VALUES;
        }
    }

    static public function editCustomerToUser($parameters) {
        if (isset($parameters['device_id'])) {
            $main_user = tblUserTable::getInstance()->findByDql('device_id=? and active=? and main_in_home=?', array($parameters['device_id'], true, true))->getFirst();
            if (!$main_user) {
                return sbValues::ERORR_USER_NOT_EXISTS;
            }
        } else {
            return sbValues::ERORR_INCORECT_VALUES;
        }

        $customer = tblCustomersTable::getInstance()->findByDql('id=? and active=?', array($main_user->getCustomerId(), true))->getFirst();
        if (!$customer) {
            return sbValues::ERORR_CUSTOMER_NOT_EXISTS;
        }

        $user = tblUserTable::getInstance()->findByDql('id=? and customer_id=?', array($parameters['user_id'], $customer->getId()))->getFirst();
        if ($user) {
            if (isset($parameters['birthday']))
                $user->setBirthday($parameters['birthday']);
            if (isset($parameters['first_name']))
                $user->setFirstName($parameters['first_name']);
            if (isset($parameters['last_name']))
                $user->setLastName($parameters['last_name']);
            if (isset($parameters['mobile']))
                $user->setMobile($parameters['mobile']);
            $user->setActive(sbValues::STATUS_ACTIVE);
            $user->setUpdateTime(sbCustomer::getCurrentTime());
            $user->save();
            return sbValues::SUCCESS;
        } else {
            return sbValues::ERORR_USER_NOT_EXISTS;
        }
    }

    public static function searchGroupByName($group_name) {
        $group_name = urldecode($group_name);
        $group = tblGroupsTable::getInstance()->findByDql('group_name=? and active=?', array($group_name, true))->getFirst();
        if ($group) {
            return $group->toArray();
        } else {
            return sbValues::NOT_FOUND;
        }
    }

    public static function connectToGroup($user_id, $group_id) {
        $user = tblUserTable::getInstance()->findByDql('id=? and active=? and main_in_home=? and group_id=?', array($user_id, true, true, 0))->getFirst();
        if ($user) {
            $group = tblGroupsTable::getInstance()->findByDql('id=? and active=?', array($group_id, true))->getFirst();

            if ($group) {
                $arrUsers = array();
                if ($group->getIsSettlements() == false) {
                    $users = tblUserTable::getInstance()->findByDql('group_id=? and active=?', array($group->getId(), true));
                    if ($users) {

                        foreach ($users as $u) {
                            array_push($arrUsers, $u->toArray());
                        }
                    }
                }

                $family = tblUserTable::getInstance()->findByDql('customer_id=? and active=?', array($user->getCustomerId(), true));
                if ($family) {
                    $count_family = 0;

                    foreach ($family as $f) {
                        $f->setGroupId($group->getId());
                        $f->save();

                        $count_family = $count_family + 1;
                    }

                    $group->setGroupUsers($group->getGroupUsers() + $count_family);
                    $group->save();
                }
            }

            return array('group' => $group->toArray(), 'group_users' => $arrUsers);
        }

        return sbValues::NOT_FOUND;
    }

    public static function getAllGroups() {
        $groups = tblGroupsTable::getInstance()->findByDql('active=?', true);
        if ($groups) {
            $arrGroup = array();

            foreach ($groups as $g) {
                $temp = array('group_id' => $g->getId(), 'group_name' => $g->getGroupName());
                array_push($arrGroup, $temp);
            }

            return $arrGroup;
        }

        return sbValues::NOT_FOUND;
    }

    public static function sendPushToGroups($user_id, $group_id, $message, $type) {
        $user = tblUserTable::getInstance()->findByDql('id=? and active=?', array($user_id, true))->getFirst();
        if ($user) {

            switch ($type) {
                case sbValues::TYPE_ALL:
                    $users = tblUserTable::getInstance()->findByDql('active=?', true);
                    break;
                case sbValues::TYPE_GROUP:
                    $users = tblUserTable::getInstance()->findByDql('group_id=? and active=?', array($group_id, true));
                    break;
                case sbValues::TYPE_EMERGENCY:
                    $users = tblUserTable::getInstance()->findByDql('group_id=? and active=? and emergency>?', array($group_id, true, 0));
                    break;
                case sbValues::TYPE_VIGILANTE:
                    $users = tblUserTable::getInstance()->findByDql('group_id=? and active=? and vigilante>?', array($group_id, true, 0));
                    break;
                case sbValues::TYPE_PARENTS:
                    $users = tblUserTable::getInstance()->findByDql('group_id=? and active=? and parents>?', array($group_id, true, 0));
                    break;
            }

            $alert = new tblAlert();
            $alert->setUserId($user_id);
            $alert->setGroupId($user->getGroupId());
            $alert->setType($type);
            $alert->setStatus(0);
            $alert->setLatitude(0);
            $alert->setLongitude(0);
            $alert->setStartTime(sbCustomer::getCurrentTime());
            $alert->save();

            $m = new tblMessage();
            $m->setUserId($user_id);
            $m->setGroupId($user->getGroupId());
            $m->setType($type);
            $m->setText($message);
            $m->setCreateTime(sbCustomer::getCurrentTime());
            $m->save();

            $msg = array(
                "type" => sbValues::NOTIF_TYPE_STANDART,
                "message" => $message,
                "time" => sbCustomer::getCurrentTime(),
                "user" => $user->toArray(),
                "alert" => array("message" => $message, "alert" => $alert->toArray())
            );

            foreach ($users as $u) {
                $notif_id = array($u->getDeviceNotifId());
                $fields = array("registration_ids" => $notif_id, "data" => $msg);
                $headers = array('Authorization: key=AIzaSyAALHIer7CiKG9ewj__aP3vlGKgg_SRXfs', 'Content-Type: application/json');
                $url = 'https://android.googleapis.com/gcm/send';
                if ($u->getDeviceType() == sbValues::DEVICE_ANDROID) {
                    self::sendAndroidPush($url, $headers, $fields);
                } else {
//                    $message = json_encode(array('type' => sbValues::NOTIF_TYPE_STANDART, 'alert' => $alert->getId(), 'message' => $m->getId()));
                    self::sendIponePush('FriendlyGuard', sbValues::NOTIF_TYPE_STANDART, $alert->getId(), $m->getId(), $notif_id);
                }
            }
        } else {
            return sbValues::NOT_FOUND;
        }
    }

    /**
     * new 30/12/13
     * @param type $birthday
     * @return type
     */
    public static function getUserAge($birthday) {
        $birthDate = explode("/", $birthday);

        $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y") - $birthDate[2]) - 1) : (date("Y") - $birthDate[2]));
        return $age;
    }

    public static function getAlertsMessage($user_id, $type, $alert_id = null, $message_id = null) {
        $user = tblUserTable::getInstance()->findByDql('id=? and active=?', array($user_id, true))->getFirst();

        if ($user) {
            switch ($type) {
                case sbValues::NOTIF_TYPE_WELCOM:
                    return array(
                        "type" => sbValues::NOTIF_TYPE_WELCOM,
                        "message" => 'הינך מוזמן להוסיף את בני משפחתך,הכנס לאזור האישי'
                    );
                case sbValues::NOTIF_TYPE_SOS:
                    return self::getArraySos($user, $alert_id);
                case sbValues::NOTIF_TYPE_HOME:
                    return self::getArrayHome($user, $alert_id);
                case sbValues::NOTIF_TYPE_CLOSE:
                    return self::getArrayCloseAlert($alert_id);
                case sbValues::NOTIF_TYPE_UPDATE:
                    return self::getArrayUpdate($alert_id, $message_id);
                case sbValues::NOTIF_TYPE_STANDART:
                    return self::getArrayMessage($message_id);
                case sbValues::NOTIF_TYPE_TO_ALERT:
                    return self::getArrayConnect($message_id, $alert_id); //message_id -> user connect to alert
            }
        } else {
            return 'user not found';
        }
    }

    public static function getArrayMessage($message_id) {
        $message = tblMessageTable::getInstance()->findByDql('id=?', $message_id)->getFirst();
        $user = tblUserTable::getInstance()->findByDql('id=?', $message->getUserId())->getFirst();

        return array(
            "type" => sbValues::NOTIF_TYPE_STANDART,
            "message" => $message->toArray(),
            "user" => $user->toArray(),
        );
    }

    public static function getArrayConnect($user_id, $alert_id) {
        $user = tblUserTable::getInstance()->findByDql('id=?', $user_id)->getFirst();
        $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
        $message = $user->getFirstName() . " " . $user->getLastName() . " " . "הצטרף לאירוע";

        return array(
            "type" => sbValues::NOTIF_TYPE_TO_ALERT,
            "message" => $message,
            "user" => $user->toArray(),
            "alert" => $alert->toArray()
        );
    }

    public static function getArrayUpdate($alert_id, $message_id) {
        if ($message_id) {
            $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
            $message = tblMessageTable::getInstance()->findByDql('id=?', $message_id)->getFirst();
            return array(
                "type" => sbValues::NOTIF_TYPE_UPDATE,
                "message" => $message->getText(),
                "alert" => $alert->toArray()
            );
        } else {
            return array(
                "error" => "alert id not found"
            );
        }
    }

    public static function getArrayCloseAlert($alert_id) {
        if ($alert_id) {
            $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
            $created = tblUserTable::getInstance()->findByDql('id=?', $alert->getUserId())->getFirst();
            if ($alert->getType() == sbValues::ALARM_SOS) {
                $message = "אירוע חירום שנפתח על ידי" . " " . $created->getFirstName() . " " . $created->getLastName() . " " . "טופל";
            } else {
                $message = "אירוע אזעקה בבית של" . " " . $created->getFirstName() . " " . $created->getLastName() . " " . "טופל";
            }

            return array(
                "type" => sbValues::NOTIF_TYPE_CLOSE,
                "message" => $message,
                "alert" => $alert->toArray()
            );
        } else {
            return array(
                "error" => "alert id not found"
            );
        }
    }

    private static function getArrayHome($user, $alert_id) {
        if ($alert_id) {
            $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
            return array(
                "type" => sbValues::NOTIF_TYPE_HOME,
                "message" => $user->getFirstName() . " " . $user->getLastName() . " " . "הפעיל אזעקה בבית",
                "alert" => $alert->toArray()
            );
        } else {
            return array(
                "error" => "alert id not found"
            );
        }
    }

    private static function getArraySos($user, $alert_id) {
        if ($alert_id) {
            $alert = tblAlertTable::getInstance()->findByDql('id=?', $alert_id)->getFirst();
            return array(
                "type" => sbValues::NOTIF_TYPE_SOS,
                "message" => $user->getFirstName() . " " . $user->getLastName() . " " . "הפעיל אירוע חירום",
                "alert" => $alert->toArray()
            );
        } else {
            return array(
                "error" => "alert id not found"
            );
        }
    }

}
